package com.example.demo.thread.ch4;

import com.example.demo.thread.util.DESEncryption;
import com.example.demo.thread.util.Tools;

/**
 * 实际测量WT/ST值Demo
 *
 * @author: htc
 * @date: Created in 14:41 2019/1/11.
 */
public class WTSTMeasureDemo implements Runnable {
    final long waitTime;

    public WTSTMeasureDemo(long waitTime) {
        this.waitTime = waitTime;
    }

    public static void main(String[] args) throws InterruptedException {
        final int argc = args.length;
        int nThreads = argc > 0 ? Integer.valueOf(args[0]) : 1;
        long waitTime = argc >= 1 ? Long.valueOf(args[0]) : 4000L;
        WTSTMeasureDemo demo = new WTSTMeasureDemo(waitTime);
        Thread[] threads = new Thread[nThreads];
        for (int i = 0; i < nThreads; i++) {
            threads[i] = new Thread(demo);
        }
        long s = System.currentTimeMillis();
        Tools.startAndWaitTerminated(threads);
        long duration = System.currentTimeMillis() - s;
        long serviceTime = duration - waitTime;
        System.out.printf("WT/ST: %-4.2f, waitTime: %dms, serviceTime: %dms, duration: %4.2fs%n",
                waitTime * 1.0f / serviceTime,
                waitTime,
                serviceTime,
                duration * 1.0f / 1000);
    }

    @Override
    public void run() {
        //模拟i/o操作
        try {
            Thread.sleep(waitTime);

            //模拟实际执行计算
            String result = null;
            for (int i = 0; i < 400000; i++) {
                result = DESEncryption.encryptAsString("it is a cpu-intensive" + i, "12345678");
            }
            System.out.printf("result:%s%n", result);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (DESEncryption.CryptoException e) {
            e.printStackTrace();
        }
    }
}
